<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

/**
 * 操作成功跳转的快捷方法
 * @access protected
 * @param mixed  $msg    提示信息
 * @param mixed  $data   返回的数据
 */
function success($msg = '', $data = '')
{

    $result = [
        'code' => 1,
        'msg'  => $msg,
        'data' => $data,
    ];

    return json_encode($result);
}

/**
 * 操作错误跳转的快捷方法
 * @access protected
 * @param mixed  $msg    提示信息
 * @param mixed  $data   返回的数据
 */
function error($msg = '', $data = '')
{
    $result = [
        'code' => 0,
        'msg'  => $msg,
        'data' => $data,
    ];

    return json_encode($result);
}

if (!function_exists('randstr')) {
    /**
     * 获得随机字符串
     * @param string $len             需要的长度
     * @param boolean $special        是否需要特殊符号
     * @return string       返回随机字符串
     */
    function randstr($len = 8, $special = false)
    {
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );

        if ($special) {
            // array_merge — 合并一个或多个数组
            $chars = array_merge($chars, array(
                "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
                "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
                "}", "<", ">", "~", "+", "=", ",", "."
            ));
        }

        $charsLen = count($chars) - 1;  //count: 数组中的单元数目
        shuffle($chars);                            //打乱数组顺序
        $str = '';
        for ($i = 0; $i < $len; $i++) {
            $str .= $chars[random_int(0, $charsLen)];    //随机取出一位  random_int:返回随机整数
        }
        return $str;
    }
}


if (!function_exists('uploads')) {
    /**
     * 单图上传
     * @param string $name            表单name值
     * @param boolean $request       请求
     * @return array       返回数组格式
     */
    function uploads($name, Request $request)
    {
        $result = [
            'code' => 0,
            'msg' => '',
            'data' => ''
        ];

        // 获取文件上传的信息
        $file = $request->file($name);

        // 通过 isValid 方法验证上传的文件是否有效
        if ($file->isValid()) {

            $ext = $file->extension(); // 根据文件的 MIME 类型确定文件的扩展名...

            $path = $file->getRealPath();  // 获取到临时文件

            // 随机生成文件名
            $filename = date("YmdHis", time()) . random_int(1000, 9999) . '.' . $ext;

            //存储文件。disk里面的public。总的来说，就是调用disk模块里的public配置
            $path_file = Storage::disk('uploads')->put($filename, file_get_contents($path));

            if ($path_file) {
                $result = [
                    'code' => 1,
                    'msg' => '上传成功',
                    'data' => '/uploads/' . $filename
                ];
            } else {
                $result['msg'] = $file->getErrorMessage();
            }
        } else {
            $result['msg'] = '暂时上传的文件';
        }

        return $result;
    }
}

// 客服端请求
if (!function_exists('httpRequest')) {
    /**
     *
     * 发起请求
     * @param $url
     * @param string $dataStr
     * @param int $isPost
     * @return bool|string
     */
    function httpRequest($url, $dataStr = "", $isPost = 0, $headers = [])
    {
        $httpInfo = [];
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22");
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // 请求头
        if (!empty($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }

        // 跳过证书检查
        if (strtolower(mb_substr($url, 0, 8, "utf-8")) == "https://") {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
        }

        if ($isPost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $dataStr);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            curl_setopt($ch, CURLOPT_URL, $url . "?" . $dataStr);
        }
        //抓取URL并把它传递给浏览器
        $response = curl_exec($ch);
        if ($response === false) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        //关闭cURL资源，并且释放系统资源
        curl_close($ch);
        return $response;
    }
}

//生成唯一订单号
if (!function_exists('build_code')) {
    /**
     * 生成唯一订单号
     * @param String $prefix 指定的订单前缀
     * @return String  返回字符串
     */

    function build_code($prefix = "")
    {
        @date_default_timezone_set("PRC");
        $order_id_main = date('YmdHis') . random_int(10000, 99999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
        $osn = $prefix . $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT); //生成唯一订单号
        return $osn;
    }
}

if (!function_exists('query_express')) {
    /**
     * $no 快递单号
     * $type 快递公司
     */
    function query_express($no, $type = null)
    {
        // 自定义返回数据
        $success = [
            'result' => false,
            'msg' => '',
            'data' => null
        ];

        // 判断单号不能为空
        if (empty($no)) {
            $success['msg'] = "快递单号不能为空";
            return $success;
        }

        $data = [
            'no' => $no
        ];

        if (!empty($type)) {
            $data['type'] = $type;
        }

        $url = "http://wuliu.market.alicloudapi.com/kdi"; //api访问链接  
        $appcode = "d73eb6df92064dac955f6148a9a4113d"; //开通服务后 买家中心-查看AppCode 
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $params = http_build_query($data);

        // 调取接口数据
        $response =  httpRequest($url, $params, 0,$headers);

        //将json 转换为 php 数组
        $output = json_decode($response, true);

        if (empty($output) || $output['status'] != 0) {
            $success['result'] = false;
            $success['msg'] = $output['msg'] ?? '未查询到物流信息';
            return $success;
        } else {
            $success['result'] = true;
            $success['msg'] = '查询物流信息成功';
            $success['data'] = $output['result']['list'];
        }
        return $success;
    }
}


if (!function_exists('uploads_list')) {
    /**
     * 多图上传
     * @param string $name            表单name值
     * @param boolean $request       请求
     * @return array       返回数组格式
     */
    function uploads_list($name, Request $request)
    {
        $result = [
            'code' => 0,
            'msg' => '',
            'data' => ''
        ];

        //数组
        $list = [];

        // 获取文件上传的信息
        $files = $request->file($name);

        foreach ($files as $file) {
            // 通过 isValid 方法验证上传的文件是否有效
            if ($file->isValid()) {

                $ext = $file->extension(); // 根据文件的 MIME 类型确定文件的扩展名...

                $path = $file->getRealPath();  // 获取到临时文件

                // 随机生成文件名
                $filename = date("YmdHis", time()) . random_int(1000, 9999) . '.' . $ext;

                //存储文件。disk里面的public。总的来说，就是调用disk模块里的public配置
                $path_file = Storage::disk('uploads')->put($filename, file_get_contents($path));

                if ($path_file) {
                    $list[] = '/uploads/' . $filename;
                } else {
                    $result['msg'] = $file->getErrorMessage();
                }
            } else {
                $result['msg'] = '暂时上传的文件';
            }
        }

        $result = [
            'code' => 1,
            'msg' => '上传成功',
            'data' => $list
        ];

        return $result;
    }
}